<template>
    <div class="tab1">
        <Form ref="data" :model="data" :rules="rule" :label-width="160" inline>
            <table style="width:100%;">
                <tr>
                    <td style="width:26%;" colspan="2">
                        <FormItem label="申请人证件号码" prop="azcp0001">
                            <Input v-model="data.azcp0001" placeholder="" :disabled="see" @on-blur="loadExistData()"
                                   class="itemStyle"/>
                        </FormItem>
                    </td>
                    <td style="width:29%;" colspan="2">
                        <FormItem label="申请人证件类型" prop="azcp0002">
                            <dictSelect :sel_val='data.azcp0002' dictCode="certificatetype"
                                        :bindData.sync="data.azcp0002" showKeys="1" class="itemStyle"/>
                        </FormItem>
                    </td>
                    <td style="width:29%;" colspan="2">
                        <FormItem label="申请人姓名" prop="azcp0003">
                            <Input v-model="data.azcp0003" placeholder="" :disabled="see" class="itemStyle"/>
                        </FormItem>
                    </td>
                    <td style="width:13%;" rowspan="4">
                        <img :src="data.azcp0519" alt="..." class="dbhead-img" @click="uploadPositiveImg('header')"/>
                    </td>
                </tr>
                <tr>
                    <td colspan="4">
                        <FormItem label="户籍地行政区划" prop="azdf0006">
                            <area-linkage :areaCode.sync="data.azdf0006" :countyDisable=false :streetDisable=false
                                          :communityDisable=false></area-linkage>
                        </FormItem>
                    </td>
                    <td colspan="2">
                        <FormItem label="户籍地邮政编码" prop="azdf0009">
                            <Input v-model="data.azdf0009" placeholder="" :disabled="see" class="itemStyle"/>
                        </FormItem>
                    </td>
                </tr>
                <tr>
                    <td colspan="4">
                        <FormItem label="户籍地详细地址" prop="azdf0500">
                            <Input v-model="data.azdf0500" placeholder="" :disabled="azdf0500Disable" class="itemLongStyle"/>
                        </FormItem>
                    </td>
                    <td colspan="2">
                        <FormItem label="联系方式" prop="azdf0011">
                            <Input v-model="data.azdf0011" placeholder="" :disabled="see" class="itemStyle"/>
                        </FormItem>
                    </td>
                </tr>
                <tr>
                    <td colspan="4">
                        <FormItem label="常住地行政区划" prop="azdf0501">
                            <area-linkage :areaCode.sync="data.azdf0501" :countyDisable=false :streetDisable=false
                                          :communityDisable = false></area-linkage>
                        </FormItem>
                    </td>
                    <td colspan="2">
                        <FormItem label="常住地邮政编码" prop="azdf0502">
                            <Input v-model="data.azdf0502" placeholder="" :disabled="see" class="itemStyle"/>
                        </FormItem>
                    </td>
                </tr>
                <tr>
                    <td colspan="4">
                        <FormItem label="常住地详细地址" prop="azdf0008">
                            <Input v-model="data.azdf0008" placeholder="" :disabled="see" class="itemLongStyle"/>
                        </FormItem>
                    </td>
                    <td colspan="3">
<!--                        <FormItem label="手机号码" prop="azdf0011">-->
<!--                            <Input v-model="data.azdf0011" placeholder="" :disabled="see" class="itemStyle"/>-->
<!--                        </FormItem>-->
                    </td>
                </tr>
                <tr>
                    <td colspan="4">
                        <FormItem label="所属地行政区划" prop="azdf0007">
                            <area-linkage :areaCode.sync="data.azdf0007" :countyDisable=countyState :streetDisable=streetState
                                          :communityDisable=communityState ></area-linkage>
                        </FormItem>
                    </td>
                    <td colspan="3">
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <FormItem label="是否有非保障人员" prop="ssca0087">
                            <dictSelect :sel_val='data.ssca0087' dictCode="yesorno" :bindData.sync="data.ssca0087"
                                        class="itemStyle"/>
                        </FormItem>
                    </td>
                    <td colspan="2">
                        <FormItem label="是否有赡(抚、扶)养人" prop="ssca0088">
                            <dictSelect :sel_val='data.ssca0088' dictCode="yesorno" :bindData.sync="data.ssca0088"
                                        class="itemStyle"/>
                        </FormItem>
                    </td>
                    <td colspan="3">
                    </td>
                </tr>
            </table>
        </Form>
        <div style="height:40px;line-height:40px;margin-top:10px;text-align: center ">
            <Button type="primary" @click="checkData()">{{checkBtnName}}</Button>
            <Button type="primary" @click="nextStep('data')" :disabled="validateStatus" :loading="loading"
                    style="margin-left:20px">下一步
            </Button>
        </div>

        <Modal v-model="ss00011ModelShow" style="margin-top:20px;" :title="yzModalTitle" :mask-closable="false"
               width="800">
            <Ss00011Check
                    :azcp0001="data.azcp0001"
                    :ssca0002="data.ssca0002"
                    :azcp0003="data.azcp0003"
                    :ss12001Id="data.ss12001Id"
                    :ss11001Id="data.ss11001Id"
                    :ss11002Id="data.ss11002Id"
                    :isRequestBackstage="ss00011ModelShow"
                    :batchNumber.sync="batchNumber"
                    :validateInfo.sync="validateInfo"
                    :validateStatus.sync="validateStatus"
                    :azdf0500.sync="data.azdf0500"
                    :checkBtnName.sync="checkBtnName"
                    :azdf0500Disable.sync="azdf0500Disable"
            />
        </Modal>

        <Modal v-model="up_pic_mol" title="图片上传" @on-ok="changeToView" :closable="false">
            <Upload multiple action="/api/ac/hdplugin/ossService/uploadBase64"
                    :before-upload="beforeUpload">
                <Button icon="ios-cloud-upload-outline">上传图片</Button>
                <span style="margin-left: 200px">建议上传小于8M的图片</span>
            </Upload>
            <img :src="temp_photo" style="width: 100%"/>
        </Modal>
        <Modal v-model="picPreviewMol.preShow" :closable="false" :styles="{top: '20px'}" width="532">
            <Carousel v-model="picPreviewMol.picIndex" style="width:500px" dots="outside" trigger="hover">
                <CarouselItem class="centerimg" v-for="(imginfo, index) in picPreviewMol.pic_urls" :key="index">
                    <img :src="imginfo" class="pre_img_style"/>
                </CarouselItem>
            </Carousel>
            <div slot="footer" style="text-align: center">
                <Button @click="picPreviewMol.preShow=false">关闭</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
  import dictSelect from '@/components/dictSelect/dictSelect.vue'
  import { postAction } from '@/api/request'
  import { IdentityCodeValid } from '@/plugins/idcardValid.js'
  import { getSign, createUpLoadFiles,compressImg } from '@/api/common'
  import DateFormat from '@/plugins/format.js'
  import Ss00011Check from '@/components/system/ss00011-check'
  import pic_header from '@/assets/images/header.jpeg'


  export default {
    name: 'application1',
    components: {
      dictSelect,
      Ss00011Check
    },
    data () {
      return {
        countyState:false,
        streetState:false,
        communityState:false,
        currentTab: 0,
          familyInfo: {},
        see:false,
        fieldsToValidate: ['azcp0001', 'azcp0002', 'azcp0003', 'azdf0006', 'azdf0501', 'azdf0008', 'azdf0007', 'azdf0011', 'ssca0087', 'ssca0088'],
        rule: {
          azcp0001: [
            { required: true, message: '请填写申请人证件号码', trigger: 'blur' }
          ],
          azcp0002: [
            { required: true, message: '请选择证件类型', trigger: 'blur' }
          ],
          azcp0003: [
            { required: true, message: '请填写申请人姓名', trigger: 'blur' }
          ],
          azdf0006: [
            { required: true, message: '请选择户籍地行政区划', trigger: 'blur' },
            { pattern: /^((?!000$).)*$/, message: '请选择完整户籍地行政区划', trigger: 'blur' }

          ],
          azdf0501: [
            { required: true, message: '请选择常住地行政区划', trigger: 'blur' },
            { pattern: /^((?!000$).)*$/, message: '请选择完整常住地行政区划', trigger: 'blur' }
          ],
          azdf0500: [
            { required: true, message: '请填写户籍地详细地址', trigger: 'blur' }
          ],
          azdf0008: [
            { required: true, message: '请填写常住地详细地址', trigger: 'blur' }
          ],
          azdf0007: [
            { required: true, message: '请选择所属地行政区划', trigger: 'blur' },
            { pattern: /^((?!000$).)*$/, message: '请选择完整所属地行政区划', trigger: 'blur' }
          ],
            azdf0011: [
                { required: true, message: '请填写联系方式', trigger: 'blur' }
            ],
          ssca0087: [
            { required: true, message: '请选择是否有非保障人员', trigger: 'blur' }
          ],
          ssca0088: [
            { required: true, message: '请选择是否有赡(抚、扶)养人', trigger: 'blur' }
          ]
        },
        url: {
          submit: '/api/ac/subsistence/ss11001Service/createDb100100Step1Submit',
          load: '/api/ac/subsistence/ss11001Service/createLoadData',
          areaInfo: '/api/ac/subsistence/ss11001Service/getUserAreaInfo',
          backWriteSs00011:'/api/ac/subsistence/ss00011Service/saveBackWriteSs00011'
        },
        loading: false,
        azcp0001BeforeChange: '',
        data: {
          azcp0002: '',
          azcp0003: '',
          azdf0006: '',
          // azdf0010: '',
          azdf0011: '',
          azdf0500: '',
          azdf0501: '',
          azdf0007: '',
          azdf0008: '',
          ssca0002: '',
          ssca0087: '',
          ssca0088: '',
          azcp0001: '',
          azcp0519: pic_header,
          azcp0578:'0', //是否通过低保事前验证  0否  1是
          ss11001Id: '',
          ss11002Id: '',
          ss12001Id: '',
        },
        temp_photo: '',
        upPicData: {},
        imgType: '',
        picPreviewMol: {
          preShow: false,
          pic_urls: [],
          picIndex: 0
        },
        up_pic_mol: false,

        checkBtnName: '人员信息(未查验)',
        validateStatus: true, //查验状态 true 未查验或查验异常 false 查验通过
        azdf0500Disable: false, //户籍地址组件是否可用，根据事前查验接口调用结果，如有户籍地址  true 反之 false
        //批次号
        batchNumber: '',
        validateInfo: '',
        //事前查验标题
        yzModalTitle: '',
        ss00011ModelShow: false,
      }
    },
    methods: {
      resetForm(){
        let that = this;
        that.data.azcp0003=null;
        that.data.azdf0009=null;
        // that.data.azdf0010=null;
        that.data.azdf0502=null;
        that.data.azdf0008=null;
        that.data.azdf0500=null;
        that.data.azdf0011=null;
        that.data.ssca0087=null;
        that.data.ssca0088=null;
        that.data.azcp0578='0';
        that.validateStatus = true;
        that.checkBtnName='人员信息(未查验)';
      },
      loadExistData () { //输入身份证号码时载入数据
        let that = this
        let azcp0001 = that.data.azcp0001
        if (azcp0001 == '') {
          that.resetForm();
          return
        }
        if (azcp0001 == that.azcp0001BeforeChange) { //证件号码未做改动，不触发载入逻辑
          return
        }
        azcp0001 = azcp0001.toUpperCase()
        that.data.azcp0001 = azcp0001

        if (!IdentityCodeValid(azcp0001)) {
          that.$Message.error('申请人身份证号码格式不合法')
          that.data.azcp0001 = null
          that.resetForm()
          return
        } else {
          that.resetForm()
          let url = that.url.load
          let dataParam = {}
          dataParam.azcp0001 = azcp0001
          dataParam.ss11001Id = that.data.ss11001Id
          dataParam.ss12001Id = that.data.ss12001Id
          dataParam.ss11001id = that.data.ss11001id
          this.data.ss11001Id = that.data.ss11001id
          dataParam.isPush = 'no'
          postAction(url, dataParam).then((res) => {
            if (res.data.data) {
              if (res.data.data.code == 1) {
                let record = res.data.data.data
                if (typeof (record) != 'undefined') {
                  that.data = Object.assign({}, record)
                }
                that.azcp0001BeforeChange = that.data.azcp0001
                that.$Message.success(res.data.data.msg)
              } else {
                that.$Message.error(res.data.data.msg)
                that.loading = false
              }
            } else {
              that.$Message.error(res.data.errmsg)
              that.loading = false
            }
          })
        }
      },
      loadStep1Data (azcp0001) { //从后面步骤返回第一步时调用
        if(azcp0001 !='') {
            let that = this
            let url = that.url.load
            let dataParam = {}
            dataParam.azcp0001 = azcp0001
            dataParam.ss11001Id = that.data.ss11001Id
            dataParam.ss12001Id = that.data.ss12001Id
            dataParam.isPush = 'no'
            postAction(url, dataParam).then((res) => {
                if (res.data.data) {
                    if (res.data.data.code == 1) {
                        let record = res.data.data.data
                        that.data = Object.assign({}, record)
                        if (that.data.azcp0578 == '1') { //已完成验证
                            that.validateStatus = false
                        } else {
                            that.validateStatus = true
                        }
                        that.azcp0001BeforeChange = that.data.azcp0001
                        that.$Message.success(res.data.data.msg)
                    } else {
                        that.$Message.error(res.data.data.msg)
                        that.loading = false
                    }
                } else {
                    that.$Message.error(res.data.errmsg)
                    that.loading = false
                }
            })
        }
      },

      checkData () {
        let that = this
        let fieldsToValidate = ['azcp0001', 'azcp0003']
        let validate = true
        let err_msg = []
        for (let item of fieldsToValidate) {
          that.$refs['data'].validateField(item, (error) => {
            if (error) {
              validate = false
              err_msg.push(error)
            }
          })
        }
        if (validate) {
          that.yzModalTitle = '事前查验-姓名：【' + that.data.azcp0003 + '】 身份证号码：【' + that.data.azcp0001 + '】'
          that.ss00011ModelShow = true
          that.azdf0500Disable = false;
        } else {
          that.$Message.error(err_msg[0])
          return
        }
      },
      backWriteSs00011: function (ss12001Id, batchNumber) {  //查验结果关联业务id
        //验证是否进行过查验
        let dataParam = {
          ss12001Id: ss12001Id,
          batchNumber: batchNumber,
        }
        postAction(this.url.backWriteSs00011, dataParam).then((res) => {
        })
      },
      nextStep: function (name) {
        this.data.azcp0519url = this.header
        let that = this
        let validate = true
        let err_msg = []
        that.loading = true

        for (let item of that.fieldsToValidate) {
          that.$refs[name].validateField(item, (error) => {
            if (error) {
              validate = false
              err_msg.push(error)
            }
          })
        }
        if (validate) {
          let dataParam = {}
          that.data.ssca0002 = that.$parent.applicationType;
          dataParam = Object.assign({}, that.data)
          let url = that.url.submit
          postAction(url, dataParam).then((res) => {
            if (res.data.data) {
              if (res.data.data.code == 1) {
                let info = res.data.data
                that.$Message.success(res.data.data.msg)
                that.familyInfo = info.data
                that.$emit('nextStep', that.familyInfo)

                that.backWriteSs00011(that.familyInfo.ss12001Id,that.batchNumber);
              } else {
                that.$Message.error(res.data.data.msg)
                that.loading = false
              }
            } else {
              that.$Message.error('数据交互异常')
              that.loading = false
            }
          }).finally(() => {

          })
        } else {
          that.$Message.error(err_msg[0])
          that.loading = false
          return
        }
      },
      changeToView () {
        this.data.azcp0519 = this.temp_photo
      },
      uploadPositiveImg (type) {
        this.temp_photo = ''
        this.imgType = type
        this.up_pic_mol = true
        if (type === 'header') {
          this.upPicData.fileName = '个人头像' + DateFormat(new Date(), 'YYYYMMDDhhmmss') + '.png'
        }
        //this.upPicData.filePath = 'itemorder/' + '/' + this.$route.params.code
        this.upPicData.filePath = 'subsistence/' + DateFormat(new Date(), 'YYYYMMDD') + '/'
      },
      beforeAvatarUpload (file) {
        return new Promise(() => {
          compressImg(file, 200).then(res => {
            let that = this
            let index = res.indexOf('base64,') + 7
            that.upPicData.file = res.substring(index)
            that.upPic(that.upPicData)
          })
        })
      },
      beforeUpload (file) {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
        if (!isJpgOrPng) {
          this.$Notice.error({ title: '上传失败', desc: '上传文件只能是 JPG 或 PNG 格式！' })
          return false
        }
        let that = this
        this.upPicData.fileName = this.upPicData.fileName + '.' + file.type.substring(6)
        if (file.size / 1024 / 1024 > 1) { // 超过1M 压缩 图片为200K
          return this.beforeAvatarUpload(file)
        }
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
          let index = reader.result.indexOf('base64,') + 7
          that.upPicData.file = reader.result.substring(index)
          that.upPic(that.upPicData)
        }
        return false
      },
      upPic (obj) {
        var time = new Date().getTime()
        this.timeStep = time.toString()
        let param = {
          filePath: obj.filePath,
          fileName: obj.fileName,
          timestamp: this.timeStep
        }
        if (param.fileName.length > 20) {
          param.fileName = param.fileName.substring(0, 20) + '.png'
        }
        getSign(param).then(res => {
          if (res.data.errcode === 0) {
            createUpLoadFiles('/api/ac/hdplugin/ossService/uploadBase64', {
              sign: res.data.data.sign,
              timestamp: this.timeStep,
              filePath: param.filePath,
              fileName: param.fileName,
              file: obj.file
            }).then(res => {
              if (res.data.errcode === 0) {
                let imgurl = res.data.data
                this.temp_photo = imgurl
              } else {
                this.$Notice.error({ title: '上传失败', desc: res.data.data.msg })
              }
            })
          } else {
            this.$Notice.error({ title: '上传失败', desc: res.data.data.msg })
          }
        })
      },
      setAreaState () {
        let that=this
        let url = that.url.areaInfo
        let dataParam = {}
        postAction(url, dataParam).then((res) => {
          if (res.data.data) {
            if (res.data.data.code == 1) {
              let record = res.data.data.data
              let arealevel=record.arealevel
              let areacode=record.areacode
              if(that.data.azdf0006==''){
                that.data.azdf0006=areacode;
              }
              if(that.data.azdf0007==''){
                that.data.azdf0007=areacode;
              }
              if(that.data.azdf0501==''){
                that.data.azdf0501=areacode;
              }
              if(arealevel==4){
                that.countyState=true
                that.streetState=true
                that.communityState=true
              }else if(arealevel==3){
                that.countyState=true
                that.streetState=true
                that.communityState=false
              }else if(arealevel==2){
                that.countyState=true
                that.streetState=false
                that.communityState=false
              }
            } else {
            }
          } else {
            that.$Message.error('数据交互异常，个人属地信息载入异常')
          }
        })
      }
    },
    created () {
        this.setAreaState();
    },
    mounted () {
      let that = this
      let params = that.$parent.familyInfo
      if (typeof (params.azcp0001) != 'undefined') {
        that.loadStep1Data(params.azcp0001)
      }else{
        that.$refs['data'].resetFields();
      }
      that.data.ssca0002 = that.$parent.applicationType;
    },
    watch:{
        'data.azcp0003': {
            handler(newName, oldName) {
                if (oldName!=''&&newName != oldName) {
                    this.validateStatus = true;
                }
            },
            immediate: true,
        },
      validateStatus(newVal, oldVal){
        if(!newVal){
          this.checkBtnName='人员信息(已查验)'
          this.data.azcp0578='1'  //事前校验通过
        }else{
          this.checkBtnName='人员信息(未查验)'
        }
      }
    }


  }

</script>

<style scoped>
    .dbhead-img {
        height: 160px;
        width: 120px;
        margin-left: 10px;
    }

    /deep/ .ivu-form-item-error-tip {
        display: none;
    }

    .ivu-form-item {
        margin-bottom: 0px;
    }

    .itemStyle {
        width: 180px
    }

    .itemLongStyle {
        width: 450px
    }
</style>
